<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 4/20/24
 * Time: 2:39 PM
 */

namespace app\common\command;

use app\common\model\media\Media;
use app\common\model\media_account\MediaAccount;
use app\common\model\recycle_report\RecycleReport;
use app\common\service\media\BdService;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\console\Command;

class PullBdReport extends Command
{
    protected function configure()
    {
        $this->setName('pull_bd_report')
            ->addOption('date', null, Option::VALUE_OPTIONAL, '拉取日期')
            ->setDescription('拉取百度媒体成本报表');
    }


    /**
     * 拉取快手报表
     *
     * @param Input $input
     * @param Output $output
     * @return bool|int|null
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        // 获取需要拉取报表的媒体账户
        $accounts = MediaAccount::with(['link', 'auth'])
            ->where([
                ['media_id', '=', Media::SOURCE_BD],
                ['status', '=', 1],
                ['promotion_link_id', '<>', 0]
            ])->select();

        if ($accounts->isEmpty()) {

            return false;
        }
        $output->writeln('开始拉取百度媒体成本，共计：' . $accounts->count() . '条');

        // 拉取时间
        if ($input->hasOption('date')) {
            $pullDate = $input->getOption('date');
        } else {
            $pullDate = date('Y-m-d', time());
        }

        $linkIds  = array_unique($accounts->column('promotion_link_id'));
        $costData = [];
        foreach ($linkIds as $linkId) {
            $costData[$linkId] = 0;
        }

        foreach ($accounts as $account) {
            $service = new BdService($account->media_auth_id);
            if (!$link = $account->link ?? []) {
                continue;
            }
            $costMoney           = $service->getAdvertiserReport(
                $account->auth_advertiser_id, $account->advertiser_id, $account->advertiser_name, $pullDate
            );
            $costData[$link->id] += $costMoney;
        }
        foreach ($costData as $key => $item) {
            $output->writeln('开始拉取百度媒体成本' . $key . '花费'.$item);

            $report = RecycleReport::where(['promotion_link_id' => $key, 'count_date' => $pullDate])->findOrEmpty();
            if (!$report->isEmpty()) {
                $report->cost_money = $item;
                $report->save();
            }
        }

        $output->writeln('拉取百度媒体成本完成');
    }

}
